<?php

# Player Battle
#
#
# 1. Get both players stats
# 2. Figure out who is the fastest
# 3. Store the fastest as $player_attacking and slower as $player_defending
#
#
#
#
#

class player_battle
{
	function __construct($player1,$player2) {
		global $db,$user_info;
       		$this->player1 = $user_info[$player1];
       		$this->player2 = $user_info[$player2];
       		$this->player1_id = $player1;
       		$this->player2_id = $player2;
       		
       		# Load the battle from the database (checks later to see if its a new battle or not)
		$this->battle_info_sql = "SELECT * FROM `user_battle` WHERE `assoc_id` = '$this->player1_id'";
		$this->battle_info = $db->return_first_result($this->battle_info_sql);

   	}
   	
   	
   	
   	
   	
   	
   	function check_alive()
   	{
   		# Function to make sure both players are alive
   		
   		if ($this->player1['assoc_id'] == $this->player2['assoc_id'])
   		{
   			// player trying to battle themselves
   			$this->error = 'Pretty difficult to battle yourself... Hmm... Naa it\'s impossible';
   			return false;
   		}
   		
   		if ($this->player1['energy'] > 0 && $this->player2['energy'] > 0)
   		{
   			return true;
   		}
   		else 
   		{
   			$this->error = 'Someone is dead.';
   			return false;
   		}
   	}
   	
   	
   	
   	
   	
   	
   	function initiate_battle($distance = 0)
   	{
   		global $db;
   		
   		if ($this->battle_info['assoc_id'] > 0)
   		{
   			//$sql = "UPDATE `user_battle` SET `distance`='$distance'";
   			
   			$this->first_battle = 0;
   			$this->battle_title = 'Last Action';
   			return true;
   		}
   		else 
   		{
	   		# Function to insert/maintain the record in user_battle
	   		$sql = "INSERT INTO `user_battle` 
			( `assoc_id` , `opponent_id` , `distance` , `log` )
			VALUES (
			'$this->player1_id', '$this->player2_id', '0', 'Battle Initiated.\n'
			)";
			$db->query($sql);
			
			//$battle_info = $db->return_first_result($battle_info_sql);
			
			$this->first_battle = 1;
			$this->battle_title = 'Battle Report';
	   		return true;
	   	}
   	}
   	
   	
   	
   	
   	
   	function speed_check($distance = 1)
   	{
   		# Checks who is the fastest 
   		# after calculating from both players speeds 
   		# and adding on reaction bonuses and taking into regard the distance
   		
   		$player1_speed = ($this->player1['speed']/$distance) + mt_rand(0,$this->player1['coordination']) + mt_rand(0,$this->player1['balance']) + mt_rand(0,$this->player1['stamina']);
   		$player2_speed = ($this->player2['speed']/$distance) + mt_rand(0,$this->player2['reflex']) + mt_rand(0,$this->player2['balance']) + mt_rand(0,$this->player2['stamina']);
   		
   		//display_var(get_defined_vars());
   		
   		if ($player1_speed > $player2_speed)
   		{
   			$this->fastest_player = $this->player1_id; // ID of fastest player
   			$this->slowest_player = $this->player2_id; // ID of slowest player
   			return true;
   		}
   		elseif ($player1_speed < $player2_speed)
   		{
   			$this->fastest_player = $this->player2_id; // ID of fastest player
   			$this->slowest_player = $this->player1_id; // ID of slowest player
   			return true;
   		}
   		else 
   		{
   			// tie
   			return false;
   		}

   	}
   	
   	
   	
   	
   	
   	function calculate_hit_power($attacker,$area,$energy_used)
   	{
   		# Function to calculate the attacking power
   		global $db;
   		
   		switch ($area)
   		{
   			case 'limbs':
   				$area_bonus = 9;
   				break;   			
   			
   			case 'torso':
   				$area_bonus = 12;
   				break;
   			
   			case 'head':
   				$area_bonus = 30;
   				break;
   			case 'defense':
   				$area_bonus = 12;
   				break;
   		}
   		
   		if ($attacker['equip_weapon'] > 0)
	   	{
	   		$weapon_id = $attacker['equip_weapon'];
			$sql = "SELECT * FROM `gladiator_items` WHERE `id` = '$weapon_id'";
			$weapon_info = $db->return_first_result($sql);
   		}
   		else 
   		{
   			$weapon_info = array();
   			$weapon_info['power'] = 0;
   		}
   		
   		# The hit power is to be a number which is approx the users (strength + weapon_strength + area_bonus)
   		$hit_power = mt_rand($attacker['strength']-5,$attacker['strength']+5) 
   		+ mt_rand($weapon_info['power']-5,$weapon_info['power']+5) 
   		+ $area_bonus + + mt_rand(0,$attacker['coordination']) 
   		+ mt_rand(0,$attacker['balance'])
   		+ mt_rand(0,$energy_used);
		return $hit_power;
   	}
   
   	
   	
   	
   	
   	
   	
    function calculate_reaction_bonus($area)
   	{
   		# Function to calculate the attacking power
   		switch ($area)
   		{
   			case 'limbs':
   				$reaction_bonus = 5;
   				break;   			
   			
   			case 'torso':
   				$reaction_bonus = 5;
   				break;
   			
   			case 'head':
   				$reaction_bonus = 10;
   				break;
   			case 'defense':
   				$reaction_bonus = 7;
   				break;
   		}
   		return $reaction_bonus;
   	}
   	
   	
   	
   	
   	
   	
   	
   	function calculate_armour_points($defender)
   	{
   		# Function to calculate the amount of points to deduct from the hit
   		if ($defender['equip_armour'] > 0)
	   	{
	   		$weapon_id = $defender['equip_armour'];
			$sql = "SELECT * FROM `gladiator_items` WHERE `id` = '$weapon_id'";
			$weapon_info = $db->return_first_result($sql);
   		}
   		else 
   		{
   			$weapon_info = array();
   			$weapon_info['power'] = 0;
   		}
   		return $weapon_info['power'];
   	}
   	
   	
   	
   	
   	
   	
   	
   	function battle_log($string = '',$distance = 1)
   	{
   		global $db;
   		if (strlen($string) == 0)
   		{
   			echo "<h2>Battle History</h2><pre><div id=\"battle_log\" style=\" 
 width:350px;
 height:115px;
 overflow:auto;
 \">". $this->battle_info['log'] . "</div></pre>" . div_scroll_to_bottom('battle_log');
   			
   		}
   		else 
   		{
   			$db->query("UPDATE `user_battle` SET `log` = CONCAT( log, '$string\n\n' ),`distance`='$distance' WHERE `assoc_id`='".USER_ID."'");
	   		
   			echo "<h2>$this->battle_title</h2>".nl2br($string);
   		}
   		return true;
   	}
   	
   	
   	
   	
   	
   	
   	
   	function hit_success($area,$energy_used)
   	{
   		global $error;
   		switch ($area)
   		{
   			case 'limbs':
   				$success = 84;
   				break;   			
   			
   			case 'torso':
   				$success = 75;
   				break;
   			
   			case 'head':
   				$success = 20;
   				break;
   			case 'defense':
   				$success = 90;
   				break;
   		}
   		if (dice_throw($success + mt_rand(0,$energy_used/7)))
   		{
   			return true;
   		}
   		else 
   		{
   			return false;
   		}
   	}
   	
   	
   	
   	
   	
   	
   	function update_energy ($assoc_id,$new_value)
   	{
   		global $db;
   		
   		$sql = "UPDATE `user_stats` SET `energy` = '$new_value' WHERE `assoc_id`='$assoc_id'";
   		$result = $db->query($sql);
   		return $result;
   	}
   	
   	
   	
   	
   	function end()
	{
		global $db;
		$sql = "DELETE FROM `user_battle` WHERE `assoc_id`='$this->player1_id'";
		return $db->query($sql);
	}
   	
   	
   	
	function add_win($who,$points)
	{
		global $db,$user_info;
		
		$points = $points + 2;
		if ($points > 9)
		{
			// level up
			$username = $user_info[$who]['username'];
			$new_level = $user_info[$who]['trainee_level'] + 1;
			
			if ($new_level > 9)
			{
				// Player can apply to become a full gladiator
				$upgrade = "\n - and can now become a gladiator";
			}
			else 
			{
				$upgrade = '';
			}
			
			echo "<pre>Thanks to the result; <b>$username</b> gained a level $upgrade</pre>";
			
			$sql = "UPDATE `user_gladiator` SET `train_wins`=train_wins+'1',`points`='0',`trainee_level`=trainee_level+'1' WHERE `assoc_id`='$who'";
		}
		else 
		{
			// just add points
			$sql = "UPDATE `user_gladiator` SET `train_wins`=train_wins+'1',`points`=points+'2' WHERE `assoc_id`='$who'";
		}
		
		$result = $db->query($sql);
		
		return $result;
	}
	
	
	function add_loss($who)
	{
		global $db;
		
		$sql = "UPDATE `user_gladiator` SET `train_losses`=train_losses+'1',`points`=points-'1' WHERE `assoc_id`='$who'";
		$result = $db->query($sql);
		
		return $result;
	}
	
	
   	function get_color($value)
   	{
   		if ($value < 10)
   		{
   			$color = '#FF0000'; // dark red
   		}
   		elseif ($value < 20)
   		{
   			$color = '#FF4900'; // red
   		}
   		elseif ($value < 40)
   		{
   			$color = '#FFAE00'; // orange/red
   		}
   		elseif ($value < 60)
   		{
   			$color = '#B1FF03'; // orange
   		}
   		elseif ($value < 80)
   		{
   			$color = '#57FF00'; // yellow/green
   		}
   		elseif ($value < 100)
   		{
   			$color = '#0FFF00'; // green
   		}
   		elseif ($value == 100)
   		{
   			$color = '#00BD29'; // dark green
   		}
   		return $color;
   	}
   	
   	
   	
   	
   	
   	function show_attack_options($energy=20,$area='',$distance=0,$pl1_energy=0,$pl2_energy=0)
	{
	        # Attack-bar
	        #
	        # To show all available attack options
	        #    (something like...)
	        #
	        # Where do you want to attack?
	        # [Head][Torso][Legs]
	        #
	        # Tactical Options
	        # [Distance yourself away][Surrender]
	        
	        $output = '';
	
	            // Include the javascript reference
	            $output .=  '<script language="JavaScript" src="/slider.js"></script>';
	            
	            
	            // include the form element
	            $output .=  '<h2>Next Action</h2><form action="'.URL_SELF.'" method="post" name="">';
	            $output .=  '<input name="energy" id="sliderValue1h" type="hidden" size="3" onchange="A_SLIDERS[0].f_setValue(this.value)">';
	            
	            $output .=  '<table class="sample" cellpadding=10 cellspacing=10 border=1><TR><TD colspan=2 align=center><b>Attack Bar </b></TD></TR><tr><td>Select an area to attack:</td><td>';
	            if ($area == 'head'){ $checked = ' checked'; } else { $checked = ''; }
	            $output .= "<input type=radio name=area value=head $checked> Head";
	            if ($area == 'torso'){ $checked = ' checked'; } else { $checked = ''; }
	            $output .=  "<BR><input type=radio name=area value=torso $checked> Torso";
	            if ($area == 'limbs'){ $checked = ' checked'; } else { $checked = ''; }
	            $output .=  "<BR><input type=radio name=area value=limbs $checked> Limbs";
	            $output .=  '</td>';
	            
	            $output .=  '<tr><td>Keeping a distance of: </td>';
	            $output .=  '<td><select name=distance>';
	            for ( $counter = 1; $counter <= 5; $counter++) 
	            {
	            	if ($distance == $counter){ $selected = ' SELECTED'; } else { $selected = ' '; }
	            	$output .= "<option value=\"$counter\" $selected> $counter meter(s)</option>";
	            }

	            $output .=  '</select></td></tr>';
	            
	            //$pl1_energy = $this->player1['energy'];
	            //$pl2_energy = $this->player2['energy'];
	            
	            $pl1_color = $this->get_color($pl1_energy);
	            $pl2_color = $this->get_color($pl2_energy);
	            
	            $graph = new BAR_GRAPH("pBar");
				$graph->values = "$pl1_energy;100, $pl2_energy;100";
				$graph->labels = "You,Opponent";
				$graph->graphBGColor = "#B0E0B0";
				$graph->graphBorder = "1px solid green";
				$graph->graphPadding = 10;
				$graph->barColors = "$pl1_color,$pl2_color";
				$graph->barBGColor = "#D0F0D0";
				$graph->labelColor = "yellow";
				$graph->labelBGColor = "#60C060";
				$graph->absValuesColor = "yellow";
				$graph->absValuesBGColor = "#60C060";
				
				
				$output .= "<tr><td colspan=2>".$graph->create()."</td></tr>";
	            
	            // Include the actual slider
	            $output .=  "<tr><td>Use Energy (%): <BR><Small>(drag pointer to desired amount)</small></td> <td><script language=\"JavaScript\">
	                var A_TPL1h = {
	                    'b_vertical' : false,
	                    'b_watch': true,
	                    'n_controlWidth': 120,
	                    'n_controlHeight': 16,
	                    'n_sliderWidth': 16,
	                    'n_sliderHeight': 15,
	                    'n_pathLeft' : 1,
	                    'n_pathTop' : 1,
	                    'n_pathLength' : 103,
	                    's_imgControl': '/img/sldr2h_bg.gif',
	                    's_imgSlider': '/img/blueh_sl.gif',
	                    'n_zIndex': 1
	                }
	            
	                var A_INIT1h = {
	                    's_form' : 0,
	                    's_name': 'sliderValue1h',
	                    'n_minValue' : 0,
	                    'n_maxValue' : 50,
	                    'n_value' : $energy,
	                    'n_step' : 1
	                }
	                new slider(A_INIT1h, A_TPL1h);
	            </script></td></tr>";
	            
	            $output .= "<TR><TD colspan=2 align=center><input type=submit value=\"Attack!\"></TD></TR></table>";
	            
	            
	            $output .=  '</form>';

	                
	        return $output;
	}

}

?>